<template>
	<div class="goodsItem">
		<CustomDialog
			:title="state.dialog.title"
			v-model:visible="state.dialog.isShowDialog"
			dialogWidth="900px"
			@close="handleGoodsDataClose"
			:dialogFooterBtn="false"
		>
			<section class="custom-dialog-body">
				<main class="main">
					<el-form ref="goodsDialogFormRef" :model="state.ruleForm" size="default" label-width="120">
						<el-tabs class="demo-tabs" @tab-click="handleClick" v-model="state.defaultActive" @tab-change="tabGoodsInfoChange">
							<el-tab-pane label="基本信息" name="base_info" class="p610">
								<template #label>
									<div class="flex" :class="{ 'color-danger': state.tabs.baseInfo }">
										<div class="tab-name">基础信息</div>
										<div class="ml5" v-if="state.tabs.baseInfo">
											<el-icon>
												<WarningFilled />
											</el-icon>
										</div>
									</div>
								</template>

								<el-form-item label="商品标题:" prop="title" :rules="{ required: true, message: '商品标题不能为空', trigger: 'blue' }">
									<el-input v-model="state.ruleForm.title" />
								</el-form-item>

								<el-form-item label="副标题:" prop="subTitle" :rules="{ required: true, message: '商品副标题不能为空', trigger: 'blue' }">
									<el-input v-model="state.ruleForm.subTitle" />
								</el-form-item>

								<el-form-item label="商品主图:" prop="showPicUrl" :rules="{ required: true, message: '商品主图不能为空', trigger: 'blue' }">
									<!-- <el-input v-model="state.ruleForm.goodsName" /> -->
									<div class="goods-image" @click="choiceFileImage(0)">
										<el-image v-if="state.ruleForm.showPicUrl != ''" :src="state.ruleForm.showPicUrl" fit="cover" class="image" />
										<el-icon v-else>
											<ele-Plus />
										</el-icon>
									</div>
								</el-form-item>

								<el-form-item label="轮播图:" prop="showgallery" :rules="{ required: true, message: '轮播图不能为空', trigger: 'blue' }">
									<div class="goods-image-gallery" @click="choiceFileImage(1)">
										<div class="goods-image img" v-for="(v, index) in state.ruleForm.showgallery">
											<el-image :src="v" fit="cover" class="image" />
											<div class="delete-img" @click.stop="deleteGalleryImage(index)">
												<el-icon>
													<ele-Delete />
												</el-icon>
											</div>
										</div>
										<div class="goods-image">
											<el-icon>
												<ele-Plus />
											</el-icon>
										</div>
									</div>
								</el-form-item>

								<el-form-item label="商品分类" prop="choiceCatalogIds" :rules="{ required: true, message: '选择商品分类', trigger: 'blue' }">
									<div class="category-tag-wrap" v-popover="catalogPopoverRef">
										<el-tag
											v-for="tag in state.choiceCatalogInfos"
											:key="tag.catalogId"
											closable
											type="info"
											style="margin: 5px"
											@close="deleteChoiceCatalogInfo(tag)"
										>
											{{ tag.catalogName }}
										</el-tag>
										<div class="category-tag-wrap-suffix">
											<el-icon>
												<ArrowDown />
											</el-icon>
										</div>
									</div>
								</el-form-item>

								<el-form-item label="商品排序:" prop="sortOrder" :rules="[{ required: true, message: '商品排序不能为空', trigger: 'blue' }]">
									<el-input v-model="state.ruleForm.sortOrder" type="number" />
								</el-form-item>

								<el-form-item label="搜索关键字:" prop="keywords">
									<el-input v-model="state.ruleForm.keywords" />
								</el-form-item>

								<el-form-item label="商品状态:" prop="status">
									<el-radio-group v-model="state.ruleForm.status">
										<el-radio :label="0">未上架</el-radio>
										<el-radio :label="1">已上架</el-radio>
										<el-radio :label="3">隐藏</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-tab-pane>
							<el-tab-pane label="价格/库存" name="stock_price" class="p610">
								<template #label>
									<div class="flex" :class="{ 'color-danger': state.tabs.stock_price }">
										<div class="tab-name">价格/库存</div>
										<div class="ml5" v-if="state.tabs.stock_price">
											<el-icon>
												<WarningFilled />
											</el-icon>
										</div>
									</div>
								</template>
								<el-form-item label="商品规格:" prop="spec">
									<el-radio-group v-model="state.ruleForm.spec" @change="changeSpec">
										<el-radio :label="0">单规格</el-radio>
										<el-radio :label="1">多规格</el-radio>
									</el-radio-group>
								</el-form-item>

								<el-form-item
									v-if="state.ruleForm.spec == 0"
									label="零售价格:"
									prop="price"
									:rules="[{ required: true, message: '商品零售价格不能为空', trigger: 'blue' }]"
								>
									<el-input v-model="state.ruleForm.price" min="0.1" step="0.1" type="number">
										<template #append> 元</template>
									</el-input>
								</el-form-item>

								<el-form-item
									v-if="state.ruleForm.spec == 0"
									label="商品原价价格:"
									prop="originalPrice"
									:rules="[{ required: true, message: '商品原价格不能为空', trigger: 'blue' }]"
								>
									<el-input v-model="state.ruleForm.originalPrice" min="0.1" step="0.1" type="number">
										<template #append> 元</template>
									</el-input>
								</el-form-item>

								<el-form-item
									v-if="state.ruleForm.spec == 0"
									label="成本价格:"
									prop="costPrice"
									:rules="[{ required: true, message: '商品成本价格不能为空', trigger: 'blue' }]"
								>
									<el-input v-model="state.ruleForm.costPrice" min="0.1" step="0.1" controls-position="right" type="number">
										<template #append> 元</template>
									</el-input>
								</el-form-item>

								<el-form-item
									v-if="state.ruleForm.spec == 0"
									label="库存展示:"
									prop="stockShowType"
									:rules="[{ required: true, message: '商品库存不能为空', trigger: 'blue' }]"
								>
									<el-radio-group v-model="state.ruleForm.stockShowType">
										<el-radio label="exact">
											<div class="flex">
												<div class="tab-name">精确展示</div>
												<div class="show_icon">
													<el-tooltip class="box-item" effect="dark" content="Top Left prompts info" placement="right-start">
														<el-icon>
															<InfoFilled />
														</el-icon>
													</el-tooltip>
												</div>
											</div>
										</el-radio>
										<el-radio label="rough">
											<div class="flex">
												<div>粗略显示</div>
												<div class="show_icon">
													<el-tooltip class="box-item" effect="dark" content="Top Left prompts info" placement="right-start">
														<el-icon>
															<InfoFilled />
														</el-icon>
													</el-tooltip>
												</div>
											</div>
										</el-radio>
									</el-radio-group>
								</el-form-item>

								<el-form-item
									v-if="state.ruleForm.spec == 0"
									label="商品库存:"
									prop="stock"
									:rules="[{ required: true, message: '商品库存不能为空', trigger: 'blue' }]"
								>
									<el-input v-model="state.ruleForm.stock" type="number" min="0">
										<template #append> 件</template>
									</el-input>
								</el-form-item>

								<el-form-item label="库存预警:" prop="stockWarning" v-if="state.ruleForm.spec == 0">
									<el-switch v-model="state.ruleForm.stockWarning" active-text="开启" inactive-text="未开启" :active-value="1" :inactive-value="0" />
									<div class="stock-warning">库存预警在未开启的状态下，使用默认库存预警</div>
								</el-form-item>

								<el-form-item
									label="预警数量:"
									prop="stockWarningCount"
									v-if="state.ruleForm.stockWarning == 1"
									:rules="[{ required: true, message: '预警库存数量不能为空', trigger: 'blue' }]"
								>
									<el-input v-model="state.ruleForm.stockWarningCount" type="number" min="1">
										<template #append> 件</template>
									</el-input>
								</el-form-item>

								<div class="many-spec" v-if="state.ruleForm.spec == 1">
									<div v-for="(spec, index) in state.ruleForm.specs" class="many-spec">
										<el-form-item
											label="规格名称:"
											:rules="{ required: true, message: '规格名称不能为空', trigger: 'blue' }"
											:prop="'specs.' + index + '.value'"
										>
											<el-input v-model="spec.value" style="width: 200px" @input="confirmSpec" />
											<div class="deleted-spec">
												<el-button size="small" @click="deleteSpec(spec)">
													<el-icon>
														<ele-Delete />
													</el-icon>
													删除规格
												</el-button>
											</div>
										</el-form-item>
										<div v-for="(specContent, idx) in spec.specContents" class="many-spec">
											<el-form-item
												label="规格值:"
												:rules="{ required: true, message: '规格值不能为空', trigger: 'blue' }"
												:prop="'specs.' + index + '.specContents.' + idx + '.value'"
											>
												<el-input v-model="specContent.value" style="width: 200px" @input="confirmSpec" />
												<div class="deleted-spec">
													<el-button size="small" @click="deleteSpecValue(spec, specContent)">
														<el-icon>
															<ele-Delete />
														</el-icon>
														删除规格值
													</el-button>
												</div>
											</el-form-item>
										</div>

										<el-form-item>
											<el-button size="small" @click="addSpecValue(spec)">
												<el-icon>
													<ele-FolderAdd />
												</el-icon>
												添加规格值
											</el-button>
										</el-form-item>
									</div>
								</div>

								<el-form-item v-if="state.ruleForm.spec == 1">
									<el-button @click="addSpec">
										<el-icon>
											<ele-FolderAdd />
										</el-icon>
										添加规格
									</el-button>

									<!-- <el-button @click="confirmSpec"> 确认规则</el-button> -->
								</el-form-item>

								<div class="many-spec many-spec-sku" v-if="state.ruleForm.spec == 1">
									<!-- 规格属性计算 -->

									<!-- <el-form-item label=""> -->
									<table class="qgg-table">
										<thead>
											<tr>
												<th v-for="header in skuHeader">{{ header }}</th>
												<th>图片</th>
												<th>零售价(元)</th>
												<th>原价(元)</th>
												<th>成本价(元)</th>
												<th>库存(个)</th>
												<th>库存预警(件)</th>
												<th>重量(kg)</th>
												<th>规格编码</th>
											</tr>
										</thead>
										<tbody>
											<tr v-for="(item, index) in state.ruleForm.goodsSkus">
												<td v-for="v in item.specification">
													<span>
														{{ v.value }}
													</span>
												</td>
												<td class="center">
													<el-form-item
														:rules="[{ required: true, message: '选择图片', trigger: 'blue' }]"
														:prop="'goodsSkus.' + index + '.image'"
														class="custom-form-item"
													>
														<div class="goods-image" @click="skuChoiceFileImage(2, item)">
															<el-image v-if="item.image != ''" :src="STATIC_URL + item.image" fit="contain" class="image" />
															<el-icon v-else>
																<ele-Plus />
															</el-icon>
														</div>
													</el-form-item>
												</td>
												<td>
													<el-form-item
														:rules="[{ required: true, message: '请输入零售价格', trigger: 'blue' }]"
														:prop="'goodsSkus.' + index + '.price'"
														class="custom-form-item"
													>
														<el-input-number v-model="item.price" :precision="2" :min="0" controls-position="right" />
													</el-form-item>
												</td>
												<td>
													<el-form-item
														:rules="[{ required: true, message: '请输入商品原价价格', trigger: 'blue' }]"
														:prop="'goodsSkus.' + index + '.originalPrice'"
														class="custom-form-item"
													>
														<el-input-number v-model="item.originalPrice" :precision="2" :min="0" controls-position="right" />
													</el-form-item>
												</td>
												<td>
													<el-form-item
														:rules="[{ required: true, message: '请输入成本价格', trigger: 'blue' }]"
														:prop="'goodsSkus.' + index + '.costPrice'"
														class="custom-form-item"
													>
														<el-input-number v-model="item.costPrice" :precision="2" :min="0" controls-position="right" />
													</el-form-item>
												</td>
												<td>
													<el-form-item
														:rules="[{ required: true, message: '请输入库存', trigger: 'blue' }]"
														:prop="'goodsSkus.' + index + '.stock'"
														class="custom-form-item"
													>
														<el-input-number v-model="item.stock" :min="0" controls-position="right" />
													</el-form-item>
												</td>
												<td class="stock_warning">
													<div class="flex flex-center-content">
														<el-switch v-model="item.stockWarning" :active-value="1" :inactive-value="0" />
														<span style="padding-left: 5px" v-if="item.stockWarning == 0">使用默认库存预警</span>
														<el-input-number
															v-if="item.stockWarning == 1"
															v-model="item.stockWarningCount"
															:min="1"
															controls-position="right"
															style="margin-left: 10px"
														/>
													</div>
												</td>
												<td>
													<el-form-item
														:rules="[{ required: true, message: '请输入商品重量', trigger: 'blue' }]"
														:prop="'goodsSkus.' + index + '.weight'"
														class="custom-form-item"
													>
														<el-input-number v-model="item.weight" :precision="2" :min="0" :step="0.1" controls-position="right" />
													</el-form-item>
												</td>
												<td>
													<el-form-item
														:rules="[{ required: true, message: '请输入商品编码', trigger: 'blue' }]"
														:prop="'goodsSkus.' + index + '.goodsCode'"
														class="custom-form-item"
													>
														<el-input v-model="item.goodsCode" controls-position="right" />
													</el-form-item>
												</td>
											</tr>
										</tbody>
									</table>
									<!-- <el-input v-model="state.ruleForm.goodsName" /> -->
									<!-- </el-form-item> -->
								</div>

								<el-form-item label="销量展示:" prop="salesShowType" :rules="[{ required: true, message: '销量展示不能为空', trigger: 'blue' }]">
									<el-radio-group v-model="state.ruleForm.salesShowType">
										<el-radio label="exact">
											<div class="flex flex-center-content">
												<div>精确展示</div>
												<div class="show_icon">
													<el-tooltip class="box-item" effect="dark" content="Top Left prompts info" placement="right-start">
														<el-icon>
															<InfoFilled />
														</el-icon>
													</el-tooltip>
												</div>
											</div>
										</el-radio>
										<el-radio label="rough">
											<div class="flex flex-center-content">
												<div>粗略显示</div>
												<div class="show_icon">
													<el-tooltip class="box-item" effect="dark" content="Top Left prompts info" placement="right-start">
														<el-icon>
															<InfoFilled />
														</el-icon>
													</el-tooltip>
												</div>
											</div>
										</el-radio>
									</el-radio-group>
								</el-form-item>
								<el-form-item label="虚拟销量:" prop="virtualSales" :rules="[{ required: true, message: '虚拟销量不能为空', trigger: 'blue' }]">
									<el-input v-model="state.ruleForm.virtualSales" type="number" min="0"></el-input>
									<span class="virtual-info">可以提高商品的销量排行榜，鼓励用户下单</span>
								</el-form-item>
								<el-form-item
									v-if="state.ruleForm.spec == 0"
									label="商品编号:"
									prop="goodsCode"
									:rules="[{ required: true, message: '商品编号不能为空', trigger: 'blue' }]"
								>
									<el-input v-model="state.ruleForm.goodsCode" />
								</el-form-item>

								<el-form-item
									v-if="state.ruleForm.spec == 0"
									label="商品重量:"
									prop="weight"
									:rules="[{ required: true, message: '商品重量不能为空', trigger: 'blue' }]"
								>
									<el-input v-model="state.ruleForm.weight" min="0" step="0.1" type="number">
										<template #append> KG</template>
									</el-input>
								</el-form-item>
							</el-tab-pane>
							<el-tab-pane label="发货设置" name="goods_send">
								<template #label>
									<div class="flex" :class="{ 'color-danger': state.tabs.goods_send }">
										<div class="tab-name">发货设置</div>
										<div class="ml5" v-if="state.tabs.goods_send">
											<el-icon>
												<WarningFilled />
											</el-icon>
										</div>
									</div>
								</template>
								<el-form-item label="配送方式:">
									<el-radio-group v-model="state.ruleForm.dispatchWay">
										<el-radio :label="0">物流快递</el-radio>
										<el-radio :label="1">货物自提</el-radio>
										<el-radio :label="2">送货上门</el-radio>
									</el-radio-group>
								</el-form-item>
								<el-form-item
									label="自提地址:"
									v-if="state.ruleForm.dispatchWay == 1"
									:rules="[{ required: true, message: '自提地址不能为空', trigger: 'blue' }]"
									prop="selfPickAddress"
								>
									<el-input v-model="state.ruleForm.selfPickAddress" />
								</el-form-item>
								<el-form-item
									label="物流快递:"
									v-if="state.ruleForm.dispatchWay == 0"
									:rules="[{ required: true, message: '物流模版不能为空', trigger: 'blue' }]"
									prop="dispatchId"
								>
									<el-select v-model="state.ruleForm.dispatchId">
										<el-option v-for="item in state.dispatchList" :label="item.dispatchName" :value="item.id" :key="item.id"></el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="货到付款:">
									<el-switch v-model="state.ruleForm.offlinePay" active-text="开启" inactive-text="未开启" :active-value="1" :inactive-value="0" />
								</el-form-item>
							</el-tab-pane>
							<el-tab-pane label="商品参数" name="goods_params">
								<template #label>
									<div class="flex" :class="{ 'color-danger': state.tabs.goods_params }">
										<div class="tab-name">商品参数</div>
										<div class="ml5" v-if="state.tabs.goods_params">
											<el-icon>
												<WarningFilled />
											</el-icon>
										</div>
									</div>
								</template>
								<el-form-item label="服务保障:" :rules="{ required: true, message: '服务保障不能为空', trigger: 'blue' }" prop="goodsService">
									<el-select v-model="state.ruleForm.goodsService" multiple="true">
										<el-option v-for="item in state.goodsServiceList" :label="item.serviceName" :value="item.id" :key="item.id"></el-option>
									</el-select>
								</el-form-item>
								<el-form-item label="参数详情:">
									<div class="sa-template-wrap">
										<div class="title flex">
											<div class="key">参数名称</div>
											<div class="value">内容</div>
											<div class="oper">操作</div>
										</div>
										<div>
											<div class="item" v-for="(item, index) in state.ruleForm.paramDetails">
												<el-form-item
													class="key"
													:rules="{ required: true, message: '商品参数名称不能为空', trigger: 'blue' }"
													:prop="'paramDetails.' + index + '.title'"
												>
													<el-input v-model="item.title" placeholder="请输入名称" />
												</el-form-item>
												<el-form-item
													class="value"
													:rules="{ required: true, message: '商品内容名称不能为空', trigger: 'blue' }"
													:prop="'paramDetails.' + index + '.content'"
												>
													<el-input v-model="item.content" placeholder="请输入内容标识" />
												</el-form-item>
												<el-form-item class="oper">
													<el-button text type="danger" link @click="deleteParamDetail(index)"> 删除</el-button>
												</el-form-item>
											</div>
										</div>
										<el-button type="primary" :icon="Plus" style="margin-top: 20px" @click="addParamDetail">增加 </el-button>
									</div>
								</el-form-item>
							</el-tab-pane>
							<el-tab-pane label="商品详情" name="goods_detail">
								<template #label>
									<div class="flex" :class="{ 'color-danger': state.tabs.goods_detail }">
										<div class="tab-name">商品详情</div>
										<div class="ml5" v-if="state.tabs.goods_detail">
											<el-icon>
												<WarningFilled />
											</el-icon>
										</div>
									</div>
								</template>
								<el-form-item label="商品详情:">
									<Editor v-model:get-html="state.editor.htmlVal" v-model:get-text="state.editor.textVal" :disable="state.editor.disable" />
								</el-form-item>
							</el-tab-pane>
						</el-tabs>

						<!-- 这块区域设置属性及参数 -->
					</el-form>
				</main>
				<footer class="footer--submit">
					<el-button @click="handleGoodsDataClose" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(goodsDialogFormRef)" size="default">{{ state.dialog.submitTxt }} </el-button>
				</footer>
			</section>

			<el-popover ref="catalogPopoverRef" trigger="click" popper-class="custom-popper">
				<el-tabs class="demo-tabs" v-model="defaultTab" @tab-change="tabChange">
					<el-tab-pane :label="item.catalogName" :name="item.id" :key="item.id" v-for="item in state.catalogData">
						<el-cascader-panel :options="item.children" :props="state.catalogProps" @change="choiceCatalog" v-model="state.ruleForm.choiceCatalogIds">
						</el-cascader-panel>
					</el-tab-pane>
				</el-tabs>
			</el-popover>
		</CustomDialog>
	</div>
	<FileChoice ref="FileChoiceRef" @choice-file="choiceFileCallBack"></FileChoice>
</template>
<script setup name="ItemDialog" lang="ts">
import type { FormInstance, TabsPaneContext } from 'element-plus';
import { reactive, ref, defineAsyncComponent, nextTick } from 'vue';
import msg from '/@/utils/messageUtils';
import { goodCatalogApi } from '/@/api/goods/catalog/index';
import { goodsApi } from '/@/api/goods/index';
import { dispatchApi } from '/@/api/shop/dispatch/index';
import { goodsServiceApi } from '/@/api/goods/service/index';
import { multiCartesian } from '/@/utils/CartesianUtils';
import { WarningFilled, Plus, ArrowDown, InfoFilled } from '@element-plus/icons-vue';
import commonFunction from '/@/utils/commonFunction';

const { randomText } = commonFunction();
import _ from 'lodash';
import { STATIC_URL } from '/@/utils/config';

const Editor = defineAsyncComponent(() => import('/@/components/editor/index.vue'));

const FileChoice = defineAsyncComponent(() => import('/@/views/file/choice/index.vue'));

const emit = defineEmits(['refresh']);

const FileChoiceRef = ref();

const goodsDialogFormRef = ref();
const catalogPopoverRef = ref();

const handleClick = (tab: TabsPaneContext, event: Event) => {
	console.log(tab, event);
};

const tabGoodsInfoChange = () => {
	console.log('tab-change');
};

const state = reactive({
	catalogData: [] as any,
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
	fullscreen: false,
	ruleForm: {
		id: '',
		title: '',
		subTitle: '',
		categoryId: '',
		brief: '',
		keywords: '',
		status: 0,
		image: '',
		shareUrl: '',
		price: 0.1,
		originalPrice: 0.1,
		sortOrder: 0,
		gallery: [] as string[],
		showPicUrl: '', //
		showgallery: [] as string[], //轮播图
		stock: 0,
		spec: 0,
		isOnSale: 0,
		specs: [] as SpecItem[],
		goodsSkus: [] as GoodsSkus[],
		dispatchId: '',
		stockWarning: 0,
		stockWarningCount: 1,
		dispatchWay: 0, // 配送方式， 自提，快递，送货上门
		expressId: 0, // 快递公司
		offlinePay: 0, // 货到付款
		goodsService: '', // 服务保障
		paramDetails: [] as any, // 参数详情
		selfPickAddress: '', // 自提地址
		choiceCatalogIds: [] as any,
		costPrice: 0.1,
		virtualSales: 0, // 虚拟销量
		weight: 0,
		salesShowType: 'exact',
		stockShowType: 'exact',
		goodsCode: '',
	},
	defaultActive: 'base_info',
	dispatchList: [] as any,
	goodsServiceList: [] as any,
	catalogProps: {
		multiple: true,
		label: 'catalogName',
		value: 'id',
		checkStrictly: true,
		emitPath: false,
	},
	editor: {
		htmlVal: '',
		textVal: '',
		disable: false,
	},
	choiceCatalogInfos: [] as ChoiceCatalogInfo[],
	tabs: {
		baseInfo: false,
		stock_price: false,
		goods_send: false,
		goods_params: false,
		goods_detail: false,
	},
});

// const specs = ref<SpecItem[]>([]);

// const specValus = ref<number[]>([]);

const defaultTab = ref();

const skuHeader = ref<string[]>([]);

const skuSpecs = ref([]);

const goodsSkus = ref<GoodsSkus[]>([]);

// 商品分类  id 对应 名称
let mapCatalogInfo = new Map();

// 大的分类下面的选中商品分类信息
let mapCatalogIdInfo = new Map();

let fileState: number = 0;

// 编辑内容
const choiceCatalog = (obj: any) => {
	console.log('obj: ', obj);
	mapCatalogIdInfo.set(defaultTab.value, obj);
	console.log('mapCatalogIdInfo: ', mapCatalogIdInfo);
	state.choiceCatalogInfos = [];
	state.ruleForm.choiceCatalogIds = [];
	mapCatalogIdInfo.forEach((v, k) => {
		console.log('k: ', k, ' , v: ', v);
		v.forEach((e) => {
			const cci: ChoiceCatalogInfo = {
				catalogId: e,
				catalogType: k,
				catalogName: mapCatalogInfo.get(e),
			};
			state.choiceCatalogInfos.push(cci);
			state.ruleForm.choiceCatalogIds.push(e);
		});
	});
};

const resolveCatalogInfos = () => {
	state.choiceCatalogInfos.forEach((e) => {
		if (!mapCatalogIdInfo.get(e.catalogType)) {
			let ids = [e.catalogId];
			mapCatalogIdInfo.set(e.catalogType, ids);
		} else {
			mapCatalogIdInfo.get(e.catalogType).push(e.catalogId);
		}
	});

	console.log('mapCatalogIdInfo: ', mapCatalogIdInfo);
};

const clearContent = () => {
	state.ruleForm.specs = [];
	skuHeader.value = [];
	goodsSkus.value = [];

	state.ruleForm.goodsSkus = [];
	state.ruleForm.gallery = [];
	state.ruleForm.image = '';
	state.ruleForm.brief = '';
	state.editor.htmlVal = '';
	state.editor.textVal = '';
	state.ruleForm.choiceCatalogIds = [];
	state.choiceCatalogInfos = [];
	mapCatalogIdInfo.clear();
};

const deleteParamDetail = (index: number) => {
	state.ruleForm.paramDetails.splice(index, 1);
};

const addParamDetail = () => {
	state.ruleForm.paramDetails.push({
		titile: '',
		content: '',
	});
};

const allChoiceCatalogInfo = () => {};

const deleteChoiceCatalogInfo = (cci: ChoiceCatalogInfo) => {
	console.log('删除信息....: ', cci);
	const index = _.findIndex(state.choiceCatalogInfos, (e) => e.catalogId == cci.catalogId);
	console.log('index: ', index);
	// delete state.choiceCatalogInfos[index];
	state.choiceCatalogInfos.splice(index, 1);
	console.log('state.choiceCatalogInfos:  ', state.choiceCatalogInfos);

	const ids = _.map(state.choiceCatalogInfos, (e) => e.catalogId);
	console.log('ids: ', ids);
	state.ruleForm.choiceCatalogIds = ids;
};

const loadDispatch = async () => {
	const { data } = await dispatchApi().searchList({});
	console.log('dispatch datas: ', data);
	state.dispatchList = data;
};

const tabChange = (value: any) => {
	// tab-change
	console.log('value: ', value);
	defaultTab.value = value;
};

const loadGoodsService = async () => {
	const { data } = await goodsServiceApi().searchList({});
	console.log('goods service datas: ', data);
	state.goodsServiceList = data;
};

const resloveMangSpecContent = (goodsAttrs: any, goodsSkusParam: any) => {
	goodsAttrs.forEach((e: any) => {
		let si: SpecItem = {
			key: randomText(),
			value: e.attribute,
			specContents: [],
		};
		e.value.forEach((element: string) => {
			si.specContents.push({
				key: randomText(),
				value: element,
			});
		});

		state.ruleForm.specs.push(si);
	});

	goodsSkusParam[0].specification.forEach((v: any) => {
		skuHeader.value.push(v.key);
	});

	goodsSkusParam.forEach((e: any) => {
		let gs: GoodsSkus = {
			image: e.image,
			showPicUrl: e.showPicUrl,
			specification: [],
			price: e.price,
			originalPrice: e.originalPrice,
			stock: e.stock,
			stockWarning: e.stockWarning,
			stockWarningCount: e.stockWarningCount,
			goodsCode: e.goodsCode,
			weight: e.weight,
			costPrice: e.costPrice,
		};
		e.specification.forEach((element: any) => {
			gs.specification.push({
				key: element.key,
				value: element.value,
			});
		});
		goodsSkus.value.push(gs);
		state.ruleForm.goodsSkus.push(gs);
	});
};

const loadGoodsDetail = async (id: string) => {
	try {
		let { data } = await goodsApi().view(id);
		console.log('data: ', data);
		state.ruleForm.id = data.id;
		state.ruleForm.categoryId = data.categoryId;
		state.ruleForm.title = data.title;
		state.ruleForm.subTitle = data.subTitle;
		state.ruleForm.gallery = data.gallery;
		state.ruleForm.showgallery = data.showgallery;
		state.ruleForm.keywords = data.keywords;
		state.editor.htmlVal = data.brief;
		state.ruleForm.brief = data.brief;
		state.ruleForm.spec = data.spec;
		state.ruleForm.stock = data.stock;
		state.ruleForm.sortOrder = data.sortOrder;
		state.ruleForm.image = data.image;
		state.ruleForm.showPicUrl = data.showPicUrl;
		state.ruleForm.price = data.price;
		state.ruleForm.originalPrice = data.originalPrice;
		state.ruleForm.status = data.status;
		state.ruleForm.choiceCatalogIds = data.catalogIds;
		state.choiceCatalogInfos = data.goodsCatalogInfoVOS;
		state.ruleForm.stockWarning = data.stockWarning;
		state.ruleForm.stockWarningCount = data.stockWarningCount;
		state.ruleForm.costPrice = data.costPrice;
		state.ruleForm.stockShowType = data.stockShowType;
		state.ruleForm.salesShowType = data.salesShowType;
		state.ruleForm.weight = data.weight;
		state.ruleForm.goodsCode = data.goodsCode;
		state.ruleForm.dispatchWay = data.dispatchWay;
		state.ruleForm.dispatchId = data.dispatchId;
		state.ruleForm.selfPickAddress = data.selfPickAddress;
		state.ruleForm.offlinePay = data.offlinePay;
		state.ruleForm.paramDetails = data.paramDetailVOS;
		state.ruleForm.goodsService = data.serviceIds;
		state.ruleForm.virtualSales = data.virtualSales;
		// state.ruleForm.ca
		if (data.spec == 1) {
			// 处理多规格
			console.log('多规格处理。。。。');
			resloveMangSpecContent(data.goodsAttrs, data.goodsSkus);
		}
		resolveCatalogInfos();
	} catch (error) {
		msg().error('查看商品详情失败，请重试');
	}
};

const onOpenDialog = async (type: string, id: string) => {
	loadDispatch();
	loadGoodsService();
	onLoadCatalogData();
	state.defaultActive = 'base_info';
	state.dialog.isShowDialog = true;
	state.dialog.type = type;
	if (type == 'add') {
		state.dialog.title = '新增商品';
		state.dialog.submitTxt = '新增';
		nextTick(() => {
			console.log('重置内容');
			goodsDialogFormRef.value.resetFields();
			goodsDialogFormRef.value.clearValidate();
			clearContent();
		});
	} else {
		state.dialog.title = '编辑商品';
		state.dialog.submitTxt = '更新';
		console.log('修改商品: ', id);
		nextTick(() => {
			goodsDialogFormRef.value.resetFields();
			goodsDialogFormRef.value.clearValidate();
		});
		loadGoodsDetail(id);
	}
};

const choiceFileImage = (state: number) => {
	fileState = state;
	FileChoiceRef.value.openFileChoiceDialog();
};

let itemState: any = null;

const skuChoiceFileImage = (state: number, item: GoodsSkus) => {
	console.log('state: ', state);
	console.log('item: ', item);
	fileState = state;
	itemState = item;
	FileChoiceRef.value.openFileChoiceDialog();
};

const choiceFileCallBack = (cfi: ChoiceFileInfo[]) => {
	if (fileState == 0) {
		console.log('图片展示');
		state.ruleForm.showPicUrl = cfi[0].visitAbsPath;
		state.ruleForm.image = cfi[0].visitRelativePath;
	} else if (fileState == 1) {
		console.log('轮播图展示列表');
		_.forEach(cfi, (e) => {
			state.ruleForm.showgallery.push(e.visitAbsPath);
			state.ruleForm.gallery.push(e.visitRelativePath);
		});

		console.log('state.ruleForm.showgallery:  ', state.ruleForm.showgallery);
	} else {
		console.log('sku 属性...', cfi);
		console.log('itemState: ', itemState);
		// sku 属性...
		itemState.image = cfi[0].visitRelativePath;
		itemState.showPicUrl = cfi[0].visitAbsPath;
	}

	console.log('选择文件回调.....  ', cfi);
};

const deleteGalleryImage = (index: number) => {
	console.log('删除index: ', index);
	state.ruleForm.showgallery.splice(index, 1);
	state.ruleForm.gallery.splice(index, 1);
};

const changeSpec = () => {
	console.log('商品规格改变.....', state.ruleForm.spec);
};

const setMapCatalogIdAndName = (obj: any) => {
	obj.forEach((e: any) => {
		mapCatalogInfo.set(e.id, e.catalogName);
		if (!_.isEmpty(e.children)) {
			setMapCatalogIdAndName(e.children);
		}
	});
};

const onLoadCatalogData = async () => {
	try {
		const { data } = await goodCatalogApi().all();
		console.log('all.....: ', data);
		defaultTab.value = data[0].id;
		data.forEach((element: any) => {
			setMapCatalogIdAndName(element.children);
		});
		console.log('defaultTab.value: ', defaultTab.value);
		state.catalogData = data;
	} catch (error) {
		msg().error('获取分类父分类失败');
	}
};

const handleGoodsDataClose = () => {
	state.dialog.isShowDialog = false;
	clearContent();
};

const deleteSpec = (item: SpecItem) => {
	const index = state.ruleForm.specs.indexOf(item);
	console.log('index: ', index);
	if (index !== -1) {
		state.ruleForm.specs.splice(index, 1);
	}
	confirmSpec();
};
const addSpec = () => {
	console.log('添加规格属性....');
	const item: SpecItem = {
		key: randomText(),
		value: '',
		specContents: [],
	};
	state.ruleForm.specs.push(item);
	// confirmSpec();
};

// 增加规格值
const addSpecValue = (spec: SpecItem) => {
	console.log('spec.specContents: ', spec.specContents);
	spec.specContents.push({
		key: randomText(),
		value: '',
	});
	confirmSpec();
};

// 删除规格值
const deleteSpecValue = (spec: SpecItem, item: SpectItemContent) => {
	console.log('规格: ', spec);
	console.log('规格值: ', item);
	const index = spec.specContents.indexOf(item);
	console.log('删除的规格位置: ', index);
	if (index !== -1) {
		spec.specContents.splice(index, 1);
	}

	confirmSpec();
};

const confirmSpec = () => {
	let specNames = []; // 属性名称

	let specValues = []; // 属性内容

	for (var i = 0; i < state.ruleForm.specs.length; i++) {
		let specValue = state.ruleForm.specs[i].specContents.map((e) => e.value);
		console.log('empty: ', _.isEmpty(specValue));

		if (!_.isEmpty(specValue)) {
			specNames.push(state.ruleForm.specs[i].value);
			specValues.push(specValue);
		}
	}

	let cartesian = multiCartesian(specValues);

	skuHeader.value = specNames;
	skuSpecs.value = cartesian;

	let result: GoodsSkus[] = [];

	console.log('cartesian: ', cartesian);
	for (var i = 0; i < cartesian.length; i++) {
		let specification: SkuSpec[] = [];

		if ('string' === typeof cartesian[i]) {
			specification.push({
				key: specNames[0],
				value: cartesian[i],
			});
			result.push({
				specification: specification,
				image: '',
				showPicUrl: '',
				price: 0,
				originalPrice: 0,
				costPrice: 0,
				stock: 0,
				weight: 0.1,
				stockWarning: 0,
				stockWarningCount: 0,
				goodsCode: '',
			});
		} else {
			for (var si = 0; si < cartesian[i].length; si++) {
				specification.push({
					key: specNames[si],
					value: cartesian[i][si],
				});
			}
			result.push({
				specification: specification,
				image: '',
				showPicUrl: '',
				price: 0,
				originalPrice: 0,
				costPrice: 0,
				stock: 0,
				stockWarning: 0,
				weight: 0.1,
				stockWarningCount: 0,
			});
		}
		console.log('类型: ', typeof cartesian[i]);
	}
	goodsSkus.value = result;
	state.ruleForm.goodsSkus = result;
	console.log('result: ', result);
};

const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	clearValidate();
	await formEl.validate(async (valid, errors) => {
		if (valid) {
			try {
				let attrs = [];

				for (let i = 0; i < state.ruleForm.specs.length; i++) {
					let atrrValues = [];
					for (let j = 0; j < state.ruleForm.specs[i].specContents.length; j++) {
						atrrValues.push(state.ruleForm.specs[i].specContents[j].value);
					}
					attrs.push({
						attribute: state.ruleForm.specs[i].value,
						value: atrrValues,
					});
				}

				if (state.ruleForm.spec === 1) {
					if (attrs.length == 0) {
						msg().error('请先创建规格参数');
						return;
					}

					if (state.ruleForm.goodsSkus.length == 0) {
						msg().error('请根据规格参数，点击确认规则，设置产品sku');
						return;
					}
				}

				if (!state.editor.htmlVal) {
					msg().error('商品详情不能为空');
					return;
				}

				if (state.dialog.type === 'add') {
					let { data } = await goodsApi().create({
						categoryId: state.ruleForm.categoryId,
						title: state.ruleForm.title,
						subTitle: state.ruleForm.subTitle,
						gallery: state.ruleForm.gallery,
						keywords: state.ruleForm.keywords,
						brief: state.editor.htmlVal,
						spec: state.ruleForm.spec,
						stock: state.ruleForm.stock,
						sortOrder: state.ruleForm.sortOrder,
						shareUrl: state.ruleForm.shareUrl,
						image: state.ruleForm.image,
						price: state.ruleForm.price,
						originalPrice: state.ruleForm.originalPrice,
						goodsAttrs: attrs,
						goodsSkus: state.ruleForm.goodsSkus,
						status: state.ruleForm.status,
						catalogIds: state.ruleForm.choiceCatalogIds,
						paramsCatalogInfos: state.choiceCatalogInfos,
						stockWarning: state.ruleForm.stockWarning,
						stockWarningCount: state.ruleForm.stockWarningCount,
						costPrice: state.ruleForm.costPrice,
						stockShowType: state.ruleForm.stockShowType,
						salesShowType: state.ruleForm.salesShowType,
						weight: state.ruleForm.weight,
						goodsCode: state.ruleForm.goodsCode,
						dispatchWay: state.ruleForm.dispatchWay,
						selfPickAddress: state.ruleForm.selfPickAddress,
						offlinePay: state.ruleForm.offlinePay,
						paramDetails: state.ruleForm.paramDetails,
						serviceIds: state.ruleForm.goodsService,
						virtualSales: state.ruleForm.virtualSales,
						dispatchId: state.ruleForm.dispatchId,
					});
				} else {
					let { data } = await goodsApi().update({
						id: state.ruleForm.id,
						categoryId: state.ruleForm.categoryId,
						title: state.ruleForm.title,
						subTitle: state.ruleForm.subTitle,
						gallery: state.ruleForm.gallery,
						keywords: state.ruleForm.keywords,
						brief: state.editor.htmlVal,
						spec: state.ruleForm.spec,
						stock: state.ruleForm.stock,
						sortOrder: state.ruleForm.sortOrder,
						shareUrl: state.ruleForm.shareUrl,
						image: state.ruleForm.image,
						price: state.ruleForm.price,
						originalPrice: state.ruleForm.originalPrice,
						goodsAttrs: attrs,
						goodsSkus: state.ruleForm.goodsSkus,
						status: state.ruleForm.status,
						catalogIds: state.ruleForm.choiceCatalogIds,
						paramsCatalogInfos: state.choiceCatalogInfos,
						stockWarning: state.ruleForm.stockWarning,
						stockWarningCount: state.ruleForm.stockWarningCount,
						costPrice: state.ruleForm.costPrice,
						stockShowType: state.ruleForm.stockShowType,
						salesShowType: state.ruleForm.salesShowType,
						weight: state.ruleForm.weight,
						goodsCode: state.ruleForm.goodsCode,
						dispatchWay: state.ruleForm.dispatchWay,
						selfPickAddress: state.ruleForm.selfPickAddress,
						offlinePay: state.ruleForm.offlinePay,
						paramDetails: state.ruleForm.paramDetails,
						serviceIds: state.ruleForm.goodsService,
						virtualSales: state.ruleForm.virtualSales,
						dispatchId: state.ruleForm.dispatchId,
					});
				}
				msg().success('操作成功');
				handleGoodsDataClose();
				emit('refresh');
			} catch (error: any) {
				msg().error('创建商品失败，请稍后重试');
			}
		} else {
			validateDataTab(errors);
		}
	});
};

const validateDataTab = (errors: any) => {
	console.log('errors: ', errors);
	_.forEach(errors, function (value, key) {
		console.log(key);
		validateRetTab(key);
	});
};

const clearValidate = () => {
	state.tabs.baseInfo = false;
	state.tabs.stock_price = false;
	state.tabs.goods_send = false;
	state.tabs.goods_params = false;
};

interface SpectItemContent {
	key: string;
	value: string;
}

interface SpecItem {
	key: string;
	value: string;
	specContents: SpectItemContent[];
}

interface SkuSpec {
	key: string;
	value: string;
}

interface GoodsSkus {
	specification: SkuSpec[];
	image: string;
	showPicUrl?: string;
	price: number;
	originalPrice: number;
	costPrice?: number;
	stock: number;
	stockWarning?: number;
	stockWarningCount?: number;
	weight?: number;
	goodsCode?: string;
}

const validateRetTab = (key: string) => {
	let baseInfos: string[] = ['goodsName', 'goodsSubTitle', 'showPicUrl', 'showgallery', 'choiceCatalogIds', 'sortOrder'];
	for (let index in baseInfos) {
		if (key.indexOf(baseInfos[index]) > -1) {
			state.tabs.baseInfo = true;
			break;
		}
	}

	let stockPrices: string[] = ['salePrice', 'vipPrice', 'costPrice', 'stock', 'virtualSales', 'goodsCode', 'weight', 'goodsSkus', 'specs'];

	for (let index in stockPrices) {
		if (key.indexOf(stockPrices[index]) > -1) {
			state.tabs.stock_price = true;
			break;
		}
	}

	let goodsSend: string[] = ['dispatchId', 'selfPickAddress'];

	for (let index in goodsSend) {
		if (key.indexOf(goodsSend[index]) > -1) {
			state.tabs.goods_send = true;
			break;
		}
	}

	let goodsParams: string[] = ['goodsService', 'paramDetails'];

	for (let index in goodsParams) {
		if (key.indexOf(goodsParams[index]) > -1) {
			state.tabs.goods_params = true;
			break;
		}
	}
};

defineExpose({
	onOpenDialog,
});
</script>

<style scoped lang="scss">
.goods-image {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 50px;
	width: 50px;
	cursor: pointer;
	border: 1px dashed var(--el-border-color-darker);

	&:hover {
		border: 1px dashed var(--el-color-primary);
	}

	.image {
		height: 100%;
		width: 100%;
	}
}

.goods-image-gallery {
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	flex-flow: row;
	// border: 1px dashed var(--el-border-color-darker);
	// &:hover {
	// 	border: 1px dashed var(--el-color-primary);
	// }
	div {
		height: 50px;
		width: 50px;
	}
}

.img {
	.delete-img {
		display: none;
	}

	display: flex;
	flex-flow: column;
	position: relative;

	&:hover {
		.delete-img {
			display: flex;
			justify-content: center;
			align-items: center;
			position: absolute;
			width: 50px;
			left: 0px;
			bottom: 0px;
			height: 20px;
			background-color: var(--el-border-color-darker);
		}
	}
}

.many-spec {
	margin-bottom: 18px;
	width: 100%;
	// border: 1px solid #dcdfe6;
}

.deleted-spec {
	margin-left: 50px;
}

.center {
	display: flex;
	justify-content: center;
}

.qgg-table {
	border-collapse: collapse;
	// width: 100%;
	border: 1px solid #c6c6c6 !important;
	margin-bottom: 20px;
	border-spacing: 0;
	table-layout: fixed;
}

.qgg-table th {
	border-collapse: collapse;
	border-right: 1px solid #c6c6c6 !important;
	border-bottom: 1px solid #c6c6c6 !important;
	background-color: #ddeeff !important;
	padding: 5px 9px;
	font-size: 14px;
	font-weight: normal;
	text-align: center;
}

.qgg-table td {
	border-collapse: collapse;
	border-right: 1px solid #c6c6c6 !important;
	border-bottom: 1px solid #c6c6c6 !important;
	padding: 5px 9px;
	font-size: 12px;
	font-weight: normal;
	text-align: center;
	word-break: break-all;
	min-width: 88px;
	box-sizing: border-box;
	// height: 40px;
}

.qgg-table td.stock_warning {
	min-width: 160px;
}

.qgg-table tr:nth-child(odd) {
	background-color: #fff !important;
}

.qgg-table tr:nth-child(even) {
	background-color: #f8f8f8 !important;
}

.my-header {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	gap: 16px;
}

.stock-warning {
	margin-left: 15px;
	color: rgba(230, 126, 34, 1);
	font-size: 12px;
}

.sa-template-wrap {
	width: 100%;
	// color: var(--sa-font)
}

.sa-template-wrap .title {
	width: inherit;
	background-color: rgba(236, 240, 241, 1);
	// background: var(--sa-table-header-bg);
	margin: 0 0 12px;
	font-size: 12px;
}

.sa-template-wrap .key,
.sa-template-wrap .value,
.sa-template-wrap .oper {
	padding: 0 16px;
	flex: 1;
}

.sa-template-wrap .oper {
	flex: none;
	width: 120px;
}

.sa-template-wrap .item {
	display: flex;
	margin-top: 16px;
}

.sa-template-wrap .item > .el-form-item {
	flex: 1;
	margin-right: 0;
	// margin-bottom: var(--sa-padding);
	padding: 0 16px;
}

.sa-template-wrap .item > .el-form-item.oper {
	flex: none;
	width: 120px;
}

.category-tag-wrap {
	flex: 1;
	min-height: 32px;
	//padding-right: 12px;
	border-radius: 4px;
	border: 1px solid #d9d9d9;
	cursor: pointer;
	position: relative;
	//padding-left: 10px;
	//padding-top: 8px;
	//padding-left: 12px;
	padding: 8px 12px;
}

.category-tag-wrap-suffix {
	width: 12px;
	height: 100%;
	position: absolute;
	right: 6px;
	top: 0;
	display: flex;
	align-items: center;
	justify-content: center;
}

.el-popper.custom-popper {
	min-width: unset;
	width: fit-content !important;
}

.many-spec-sku {
	width: 100%;
	overflow: auto;
}

.show_icon {
	margin-left: 12px;
}

.tab-name {
	font-size: var(--el-font-size-base);
	font-weight: 500;
	height: var(--el-tabs-header-height);
}

.virtual-info {
	color: rgb(230, 126, 34);
}
</style>
